package com.enjoylearning.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.enjoylearning.auth.service.AuthService;
import com.enjoylearning.ucenter.mapper.XcMenuMapper;
import com.enjoylearning.ucenter.mapper.XcUserMapper;
import com.enjoylearning.ucenter.model.dto.AuthParamsDto;
import com.enjoylearning.ucenter.model.dto.XcUserExt;
import com.enjoylearning.ucenter.model.po.XcMenu;
import com.enjoylearning.ucenter.model.po.XcUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private XcMenuMapper xcMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //将json串转为AuthParamDto
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证的参数不符合要求");
        }

        //认证类型
        String authType = authParamsDto.getAuthType();
        //根据认证方式判断使用哪个bean
        String beanName = authType+"_authService";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //调用对应方法进行认证
        XcUserExt execute = authService.execute(authParamsDto);


        String username = authParamsDto.getUsername();
        //查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) {
            return null;
        }

        UserDetails userPrinciple = getUserPrinciple(execute);
        return userPrinciple;
    }

    public UserDetails getUserPrinciple(XcUserExt xcUser) {
        //若查到了用户，将用户信息封装成一个UserDetails返回给框架，由框架进行密码比对
        String password = xcUser.getPassword();
        //权限
        //查询权限，将权限加入到权限数组中
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        String[] authorities = {};
        if (!xcMenus.isEmpty()) {
            List<String> permissions = xcMenus.stream().map(XcMenu::getCode).collect(Collectors.toList());
            authorities = permissions.toArray(authorities);
        }
        //将用户信息转为json
        xcUser.setPassword(null);  //避免敏感数据
        String userJson = JSON.toJSONString(xcUser);
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
